package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.ActTaskCommentEntity;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.mapper.KingPurchaseTermsMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.IActTaskCommentService;
import com.ly.heart.service.IKingPurchaseTermsService;
import org.springframework.stereotype.Service;
import com.ly.heart.domain.KingPurchaseTermsEntity;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 金蝶-采购条款Service业务层处理
 * @author cxl
 * @date 2024-06-23
 */
@Service
public class KingPurchaseTermsServiceImpl extends ServiceImpl<KingPurchaseTermsMapper, KingPurchaseTermsEntity> implements IKingPurchaseTermsService {

    @Resource
    private IActModelService iActModelService;
    @Resource
    private IActTaskCommentService iActTaskCommentService;

    /**
     * 查询金蝶-采购条款
     * @param id 金蝶-采购条款ID
     * @return 金蝶-采购条款
     */
    @Override
    public KingPurchaseTermsEntity selectKingPurchaseTermsEntityById (String id) {
        return this.getById ( id );
    }

    /**
     * 查询金蝶-采购条款列表
     * @param kingPurchaseTermsEntity 金蝶-采购条款
     * @return 金蝶-采购条款
     */
    @Override
    public AjaxResult selectKingPurchaseTermsEntityList (KingPurchaseTermsEntity kingPurchaseTermsEntity) {
        LambdaQueryWrapper<KingPurchaseTermsEntity> kingPurchaseTermsEntityLambdaQueryWrapper = new LambdaQueryWrapper<> ();
        if ( kingPurchaseTermsEntity.getType () != null ) {
            kingPurchaseTermsEntityLambdaQueryWrapper.eq ( KingPurchaseTermsEntity :: getType, kingPurchaseTermsEntity.getType () );
        }
        kingPurchaseTermsEntityLambdaQueryWrapper.eq ( KingPurchaseTermsEntity :: getIsUsed, ConstUtil.IS_USED_YES );
        IPage<KingPurchaseTermsEntity> page = this.page ( new Page<> ( kingPurchaseTermsEntity.getPage (), kingPurchaseTermsEntity.getLimit () ), kingPurchaseTermsEntityLambdaQueryWrapper );
        List<KingPurchaseTermsEntity> records = page.getRecords ();
        records.forEach ( term -> {
            //处理最后一个审批人
            ActTaskCommentEntity actTaskCommentEntity = iActTaskCommentService.queryLastComment ( term.getInstanceId () );
            if ( actTaskCommentEntity != null ) {
                term.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                term.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( term.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                term.setCurrentTask ( currentTask );
            } );
        } );
        return AjaxResult.success ( page );
    }

    /**
     * 新增金蝶-采购条款
     * @param kingPurchaseTermsEntity 金蝶-采购条款
     * @return 结果
     */
    @Override
    public AjaxResult draft (KingPurchaseTermsEntity kingPurchaseTermsEntity) {
        kingPurchaseTermsEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ( new LambdaQueryWrapper<KingPurchaseTermsEntity> ().eq ( KingPurchaseTermsEntity :: getType, kingPurchaseTermsEntity.getType () ) );
        kingPurchaseTermsEntity.setCode ( ( kingPurchaseTermsEntity.getType () == 1 ? "CGTK" : "XSTK" ).concat ( String.format ( "%08d", count ) ) );
        kingPurchaseTermsEntity.setCreateTime ( DateUtils.getNowDate () );
        kingPurchaseTermsEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        boolean save = this.save ( kingPurchaseTermsEntity );
        if ( ! save ) {
            throw new CustomException ( kingPurchaseTermsEntity.getType () == 1 ? "暂存采购条款失败" : "暂存销售条款失败" );
        }
        return AjaxResult.success ( kingPurchaseTermsEntity.getType () == 1 ? "暂存采购条款成功" : "暂存销售条款成功", kingPurchaseTermsEntity.getId () );
    }

    public AjaxResult submit (KingPurchaseTermsEntity kingPurchaseTermsEntity) {
        if ( StringUtils.isBlank ( kingPurchaseTermsEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据！" );
        }
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( kingPurchaseTermsEntity.getId () ).
                setBusinessType ( kingPurchaseTermsEntity.getBusinessType () ).setModelId ( kingPurchaseTermsEntity.getModelId () ).
                setBusinessName ( "采购销售条款".concat ( kingPurchaseTermsEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        boolean update = this.update ( new LambdaUpdateWrapper<KingPurchaseTermsEntity> ().
                set ( KingPurchaseTermsEntity :: getInstanceId, instanceId ).
                set ( KingPurchaseTermsEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                eq ( KingPurchaseTermsEntity :: getId, kingPurchaseTermsEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交条款失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 修改金蝶-采购条款
     * @param kingPurchaseTermsEntity 金蝶-采购条款
     * @return 结果
     */
    @Override
    public AjaxResult updateKingPurchaseTermsEntity (KingPurchaseTermsEntity kingPurchaseTermsEntity) {
        kingPurchaseTermsEntity.setChangeTime ( DateUtils.getNowDate () );
        boolean b = this.updateById ( kingPurchaseTermsEntity );
        if ( ! b ) {
            throw new CustomException ( "修改条款失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 批量删除金蝶-采购条款
     * @param ids 需要删除的金蝶-采购条款ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingPurchaseTermsEntityByIds (String[] ids) {
        boolean update = this.update ( new LambdaUpdateWrapper<KingPurchaseTermsEntity> ().
                set ( KingPurchaseTermsEntity :: getIsUsed, ConstUtil.IS_USED_NO ).in ( KingPurchaseTermsEntity :: getId, ids ) );
        if ( ! update ) {
            throw new CustomException ( "删除失败！" );
        }
        return AjaxResult.success ( "删除成功" );
    }

    @Override
    public AjaxResult disabled (String id) {
        KingPurchaseTermsEntity byId = this.getById ( id );
        if ( byId == null ) {
            return AjaxResult.error ( "无此数据！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<KingPurchaseTermsEntity> ().
                set ( KingPurchaseTermsEntity :: getIsDisabled, byId.getIsDisabled () == 1 ? 2 : 1 ).
                set ( KingPurchaseTermsEntity :: getDisabledTime, DateUtils.getNowDate () ).
                eq ( KingPurchaseTermsEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( byId.getIsDisabled () == 1 ? "禁用银行失败！" : "解禁银行失败！" );
        }
        return AjaxResult.success ();
    }
}
